// 常用请求
var COMMON_URL = {
		uploadImage: "http://file.jhjvip.cn:8888/image-server/uploadImage",
		//getImage: "http://file.jhjvip.cn:8080/image-server/getImage?file=",
		//获取代码表, example实例：basePath + "/inner/getCodeDetail?code=T_DM_SEX&type=0"
		getCode: basePath + '/sys/inner/getCodeDetail',
		getUserFunc: basePath + '/sys/resource!getUserFunc.action',
		uploadifySwf: basePath + '/static/plugin/uploadify/js/uploadify.swf',
		upload: basePath + '/fileUpload/uploadWithDB',
		image: basePath + '/fileDownload/getImage',
		download: basePath + '/fileDownload/download',
		delFile: basePath + '/fileUpload/delFile',
		fileInfo: basePath + '/fileUpload/getFileInfo',
		showFile: basePath + '/fileDownload/initShowOffice'
};

var CommonUtil = {
	// 根据传入的权限标识,获取该菜单下的功能权限。
    getPermission: function (permit) {
    	if (top.globalPermission && top.globalPermission[permit]) {
    		return top.globalPermission[permit];
    	}
    	return [];
    },    
    //格式化日期
    formatDate: function(time) {
        var date = new Date(time),
            year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate(),
            hours = date.getHours(),
            minutes = date.getMinutes(),
            seconds = date.getSeconds();
        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    },
    //图片展示
    showImages : function (options){
        if ($("#imagesArea").length > 0){
            $("#imagesArea").empty();
        } else {
            $("body").append('<div id="imagesArea" style="display: none"></div>');
        }
        $.each(options.images,function(){
            $('<a>').attr({
                "href" : this.href,
                "data-lightbox" : this.group || "group1",
                "data-title": this.title || "默认"
            }).appendTo($("#imagesArea"));
        });
        if (options.defaultShow){
            $("#imagesArea a[data-title=" + options.defaultShow + "]").click();
        } else {
            $("#imagesArea a").first().click();
        }
    }
};

var upLoadUtil = {
		
	"initUplod" : function (config){
		if(config && config.items){
			upLoadUtil.saveConfig(config);
			$.each(config.items, function(index,item){
				// 初始化隐藏框
				var hiddenFileIds = "";
				if(item.hiddenFileIds){
					hiddenFileIds = item.hiddenFileIds;
				}else{
					hiddenFileIds = item.id + "_fileIds";
				}
				createHiddenInput(item.id,hiddenFileIds,'');
				$('#' + item.id).uploadify({
					'height' : 22,
					'width' : 90,
					'method' : 'post', // 文件提交方法, 默认为post
					'auto' : true,
					'swf' : COMMON_URL.uploadifySwf,
					'uploader' : COMMON_URL.upload ,
					'fileSizeLimit' : item.fileSizeLimit,
					'fileTypeExts' : item.fileTypeExts, //该设置会让windows弹出的窗口自动过滤不符合后缀的文件名。
					'progressData' : 'speed', //上传时进度条下方的显示形式： 速度或百分比。默认：percentage
					'buttonText' : '添加文件',
					'fileTypeDesc' : '支持的格式', //选中文件时右下角文件类型的说明
					'queueSizeLimit' : item.queueSizeLimit, // 队列长度
					'removeCompleted' : false,
					'uploadLimit' : item.uploadLimit,// 最大上传数量 
					'multi' : item.multi,
					'wmode' : 'window',           
					'formData' : {
						'tableName' : item.tableName,
						'id' : $("#id").val(),
						'jsessionid' : config.sessionId,
						'field' : item.field
					},
					'fileObjName' : 'uploadFile',
					'onUploadStart': function (file) {
			        },
					'onQueueComplete' : function(queueData) {
					},
					'onSelect': function(file){
					},
					'onCancel': function(file){
					},
					'onClearQueue': function(){
					},
					"onDialogOpen" : function(){
						return false;
					},
					'onUploadSuccess' : function(file, data, response){
						var jsonData = $.parseJSON(data);
						if(jsonData && jsonData.data){
							createHiddenInput(item.id,hiddenFileIds,jsonData.data.fileId);
							var cancel = $("#"+file.id + " .cancel a");
							if (cancel) {
								cancel.on('click',function () {
									// 在这此处处理...
									// 通过uploadify的settings方式重置上传限制数量
									var oldMaxNumber =  $('#' + item.id).uploadify('settings','uploadLimit');
									$('#' + item.id).uploadify('settings','uploadLimit', oldMaxNumber + 1);
									$(this).hide();
									var $hiddenFileIds = $("#" + item.id).siblings("input[name="+ hiddenFileIds.replace(/\./g, '\\.')+"]").first();
									upLoadUtil.delFileOnServer(jsonData.data.fileId,$hiddenFileIds,config.sessionId,config.formId);
									upLoadUtil.uploadIsEnabled(config.formId);
								});
							}
							upLoadUtil.uploadIsEnabled(config.formId);
							if(config.onUploadSuccess){config.onUploadSuccess.call(this,jsonData.data.filePath);}
						}else{
							alert("上传出错！");
						}
					},
					'onSelect' : function(){
					},
					'onDialogClose' : function(){
					},
					'onSelectError' :function(file,errorCode,msg){
						if (msg == 0){
							this.queueData.errorMsg = "上传文件最大个数为: " + item.uploadLimit;
						}
					}
				});
			});
		}
		// 创建隐藏域，并设置值
		function createHiddenInput(plugInId,name,value){
			if($("input[name=" + name.replace(/\./g, '\\.') +"]").length > 0){
				var $input = $("#"+plugInId).siblings("input[name="+ name.replace(/\./g, '\\.') +"]").first();
				if($input.val()!=''){
					$input.val($input.val() + "," + value);
				}else{
					$input.val(value);
				}
			} else {
				$("<input>").attr({
					"name" : name,
					"type" : "hidden"
				}).val(value).insertBefore($('#' + plugInId));
			}
		};
	},
	"saveConfig" : function (config){
		var configs = {};
		 if ($("input[name=uploadify-info]").length > 0){
			oldConfigs = $("input[name=uploadify-info]").first().data("uploadify");
			oldConfigs[config.formId] = config;
			$("input[name=uploadify-info]").first().data("uploadify",oldConfigs);
		} else {
			configs[config.formId]=config;
			$("<input>").attr({
				"name" : "uploadify-info",
				"type" : "hidden"
			}).appendTo($("body")).data("uploadify",configs);
		} 
	},
	// 删除服务器文件
	"delFileOnServer" : function (fileId,$hiddenFileName,sessionId,formId){
		$.sajax({
			type : "get",
			url : COMMON_URL.delFile,
			onLoadSuccess : function(data){
				if (data.result == "success"){
					upLoadUtil.removeFileInfo(fileId, $hiddenFileName);
					upLoadUtil.uploadIsEnabled(formId);
				}
			},
			data:{
				"id" : fileId
			}
		});
	},
	// 删除隐藏域中对应的文件名和文件路径
	"removeFileInfo" : function (fileId, $hiddenFileName){
		if ( $hiddenFileName.val()){
			var names = $hiddenFileName.val().split(",");
			for(var i = 0; i < names.length; i++){
				if(fileId === names[i]){
					names.splice( i, 1 );
					break;
				}
			}
			$hiddenFileName.val(names.join(","));
		}
	},
	// 将删除文件的路径放入隐藏域，并无实际删除操作
	"delFile" : function (fileId,formId,field, object){
		// ----- 删除列表项 删除文件路径 加入隐藏域
		if($("#" + formId + " input[name=delFileIds]").length > 0){
			var oldValue = $("#" + formId + " input[name=delFileIds]").first().val();
			$("#" + formId + " input[name=delFileIds]").first().val(oldValue + "," + fileId); 
		}else{
			var $input = $("<input>").attr({
				"name" : "delFileIds",
				"type" : "hidden"
			}).val(fileId); 
			$('#' + formId).append($input);
		}
		$(object).parent().remove();
		
		// ----- 更改可上传文件大小
		var item = upLoadUtil.getItemByField(field,formId);
		var oldMaxNumber = $('#' + item.id).uploadify('settings','uploadLimit');
		$('#' + item.id).uploadify('settings','uploadLimit', oldMaxNumber + 1);
		
		// ----- 对列表框隐藏框值进行去除
		var hiddenFileIds = "";
		if (item.hiddenFileIds){
			hiddenFileIds = item.hiddenFileIds;
		}else{
			hiddenFileIds = item.id + "_filePath";
		}
		var $hiddenFileIds = $("#" + item.id).siblings("input[name="+ hiddenFileIds.replace(/\./g, '\\.')+"]").first();
		upLoadUtil.removeFileInfo(fileId,$hiddenFileIds);
		
		upLoadUtil.uploadIsEnabled(formId);// 按钮是否可用
	},
	// 必填验证
	"validateFiles" : function (ids,formId){
		function validateFileItem (id,formId){
		 	var result = true,hasFileList = true;
			if ($("input[name=uploadify-info]").length > 0){
				var items = $("input[name=uploadify-info]").first().data("uploadify")[formId].items;
				$.each(items, function(index,item){
					if (id === item.id && item.required){
						// 文件列表是否存在已经上传文件
						hasFileList = upLoadUtil.getListNumberByField(item.field)> 0 ? true: false;
						if(item.hiddenFileIds){
							result = ($("#" + item.id).siblings("input[name="+ item.hiddenFileIds.replace(/\./g, '\\.') + "]").length > 0 && $("#" + item.id).siblings("input[name="+ item.hiddenFileIds.replace(/\./g, '\\.') + "]").first().val() != "")? true: false;
						} else {
							result = ($("#" + item.id).siblings("input[name="+ item.id + "_fileIds" + "]").length > 0 && $("#" + item.id).siblings("input[name="+ item.id + "_fileIds" + "]").first().val() != "")? true: false;
						}
						return result || hasFileList;
					}
				});
			}
			return result || hasFileList;
		};
		result = true;
		$.each(ids,function(index,value){
			result = validateFileItem(value,formId);
			return result;
		});
		if(!result){
			$.sdialog({
				type: 'warn',
				msg: '请选择上传文件，并上传!',
				owner: window
			});
		}
		return result;
	},
	// 获得列表中某一字段的附件数量
	"getListNumberByField": function getListNumberByField(field){
		return	$("#" + field +"_field div[class*=upload-item-file]").length;
	},
	// 上传按钮是否可用
	"uploadIsEnabled" :function (formId){
		var configs = $("input[name=uploadify-info]").first().data("uploadify")[formId];
		$.each(configs.items,function(index,item){
			var stateNumber = $("#"+item.id).data('uploadify').queueData.queueLength;
			var exitsNumber = upLoadUtil.getListNumberByField(item.field);
			var maxNumber = item.uploadLimit;
			if(stateNumber + exitsNumber >= maxNumber){
				$("#" + item.id).uploadify("disable",true);
			}else{
				$("#"+item.id).uploadify("disable",false);
			}
		});
	},
	"setPluginProperties" : function(id, length) {
		$(id).uploadify('settings', 'uploadLimit');
		var oldMaxNumber = $(id).uploadify('settings', 'uploadLimit');
		$(id).uploadify('settings', 'uploadLimit', oldMaxNumber - length);
	},
	// 创建文件列表
	"createFileList": function (files,formId){
		$.each(files,function (key,value){
			var config = upLoadUtil.getItemByField(key,formId);
			createFieldHtml(config);
			$.each(value,function(index,fileInfo){
				createFileItem(fileInfo,config,formId);
			});
			try {// 因uploadify文件没有初始化完成方法，所以用这种方法判断插件是否加完完成，以便调用其相关方法
				upLoadUtil.setPluginProperties('#' + config.id, value.length);
			} catch (e) {
				try {
					setTimeout("upLoadUtil.setPluginProperties('#" + config.id
							+ "','" + value.length + "')", 500);
				} catch (e) {
					setTimeout("upLoadUtil.setPluginProperties('#" + config.id
							+ "','" + value.length + "')", 1000);
				}
			}
		});
		try {// 因uploadify文件没有初始化完成方法，所以用这种方法判断插件是否加完完成，以便调用其相关方法
			upLoadUtil.uploadIsEnabled(formId);
		} catch (e) {
			try {
				setTimeout("upLoadUtil.uploadIsEnabled('" + formId + "')", 500);
			} catch (e) {
				setTimeout("upLoadUtil.uploadIsEnabled('" + formId + "')", 1000);
			}
		}
		// 创建文件每一项 文件名称、大小、下载、删除
		function createFileItem(fileInfo,config,formId){
			var suffix = fileInfo.name.substring(fileInfo.name.lastIndexOf("."));
			var shortName = fileInfo.name;
			if (fileInfo.name.length > 15){
				shortName = shortName.substring(0,10)+"..." + suffix; 
			}
			var html = '<div class="upload-item-file"><span class="upload-fileName" title="' + fileInfo.name + '">' + shortName + '</span>';
			html += '<span class="upload-fileSize">' + fileInfo.size + '</span>';
			html += '<a class="upload-action" title="删除" href ="javascript:;" onclick="upLoadUtil.delFile(\'' + fileInfo.id +'\',\''+ formId +'\',\''+ config.field +'\',this)"><i class="icon icon-delete"></i></a>';
			html += '<a class="upload-action" title="下载" href="javascript:;" onclick="upLoadUtil.downLoad(\'' + fileInfo.path + '\',\'' + fileInfo.name + '\',\'' + formId +'\')"> <i class="icon icon-download"></i>  </a>';
			if ($.inArray(suffix.toUpperCase(), upLoadUtil.imagsSuffix.concat(upLoadUtil.documentSuffix)) >= 0 ){
				html += '<a class="upload-action" title="预览" href ="javascript:;" onclick="upLoadUtil.viewDocument(\'' + fileInfo.path + '\',\'' + fileInfo.name + '\',\'' + formId +'\')"><i class="icon icon-eye"></i></a>';
			}
			$('#' + config.field + "_field").append(html + "</div>");
		};
		// 文件外层DIV
		function createFieldHtml(config){
			var $div = $("<div>").attr({
				"id" : config.field + "_field"
			}).addClass("upload-container");
			$("#"+config.id).next().after($div);
		}
	},
	// 根据字段名称获得相应的配置
	"getItemByField" : function (field,formId){
		var items = $("input[name=uploadify-info]").first().data("uploadify")[formId].items;
		var item = null;
		$.each(items,function(index,value){
			if (value.field === field){
				item = value;
				return false;
			}
		});
		return item;
	},
	// 下载文件
	"downLoad" : function (filePath, fileName, formId){
		var sessionId = $("input[name=uploadify-info]").first().data("uploadify")[formId].sessionId;
		if($("#downForm").length <= 0){
			var $form = $("<form>").attr({
				"id" : "downForm",
				"method" : "post"
			});
			$("body").append($form);
		}
		$("#downForm").attr({
			"action" :	COMMON_URL.download + '?filePath=' + filePath 
		});
		$('#downForm').append($("<input>").attr({"type":"hidden","value":fileName,"name":"fileName"}));
		$('#downForm').submit(); 
	},
	"imagsSuffix" : [".JPG",".JPEG",".PNG",".BMP"],
	"documentSuffix" : [".TXT",".DOC",".DOCX",".PPT",".XLS",".XLSX",".PDF",".SWF"],
	// 创建查看页面的HTML
	"createViewHtml" : function (config,files){
		upLoadUtil.saveConfig(config);
		$.each(files, function(key, value){
			//var item = upLoadUtil.getItemByField(key,config.formId);
			var $outer = $("<div>").attr({
				"id" : key + "_field"
			}).addClass("upload-container").appendTo($("#" + key));
			$.each(value, function(key1,value1){
				createFileHtml(value1,$outer,config.formId,key);
			});
		});
		function createFileHtml(fileInfo,$outer,formId,field){
			var suffix = fileInfo.name.substring(fileInfo.name.lastIndexOf("."));
			var shortName = fileInfo.name;
			if (fileInfo.name.length > 15){
				shortName = shortName.substring(0,10)+"..." + suffix; 
			}
			var html = '<div class="upload-item-file"><span class="upload-fileName" title="' + fileInfo.name + '">' + shortName + '</span>';
			html += '<span class="upload-fileSize">' + fileInfo.size + '</span>';
			html += '<a class="upload-action" title="下载" href="javascript:;" onclick="upLoadUtil.downLoad(\'' + fileInfo.path + '\',\'' + fileInfo.name + '\',\'' + formId +'\')"> <i class="icon icon-download"></i></a>';
			if ($.inArray(suffix.toUpperCase(), upLoadUtil.imagsSuffix.concat(upLoadUtil.documentSuffix)) >= 0 ){
				html += '<a class="upload-action" title="预览" href ="javascript:;" onclick="upLoadUtil.viewDocument(\'' + fileInfo.path + '\',\'' + fileInfo.name + '\',\'' + config.formId +'\')"><i class="icon icon-eye"></i></a>';
			}
			html += '</div>';
			$outer.append(html);
		}
	},
	"getFileInfo" : function(fileIds, field){
		var fileInfos = {};
		$.sajax({
			type : "get",
			async : false,
			url : COMMON_URL.fileInfo,
			onLoadSuccess : function(data){
				if (data.result == "success"){
					fileInfos = data.data;
				}
			},
			data:{
				"fileIds" : fileIds,
				"field" : field
			}
		});
		return fileInfos;
	},
	// 文档预览
	"viewDocument" : function (filePath,fileName,formId){
		var sessionId = $("input[name=uploadify-info]").first().data("uploadify")[formId].sessionId;
		var suffix = filePath.substring(filePath.lastIndexOf("."));
		// 如果是图像类
		if ($.inArray(suffix.toUpperCase(), upLoadUtil.imagsSuffix) >= 0){
			var options = {
			 "images" : [{
				 "href" : COMMON_URL.image + '?filePath=' + filePath,
				 "title" : fileName
				 }]
			};
			window.top.CommonUtil.showImages(options);
		} 
		// 如果是office类
		if ($.inArray(suffix.toUpperCase(), upLoadUtil.documentSuffix) >= 0){
			window.open(COMMON_URL.showFile + '?filePath=' + filePath);
		}
	}
};


//去除开头结尾空格
function trimSpace(value) {
    if(value) {
        var reg = /(^\s+)|(\s+$)/g;
        if(reg.test(value)){
            value = $.trim(value);
        }
    }
    return value;
}

//防止在输入框内按enter键返回到主页面
document.onkeydown = check;
function check(e) {
    var ev = e || window.event,  //获取event对象
        obj = ev.target || ev.srcElement, //获取事件源
        t = obj.type || obj.getAttribute('type'), //获取事件源类型
        vReadOnly = obj.readOnly,  //只读
        vDisabled = obj.disabled;  //不可用

    //处理undefinde值
    vReadOnly = (vReadOnly == 'undefined') ? false : vReadOnly;
    vDisabled = (vDisabled == 'undefined') ? false : vDisabled;

    //当按backspace键时，事件类型为密码、单行、多行、文件类型时
    //并且readOnly为true或disabled为true时，退格失效
    var flag1 = (ev.keyCode == 8 &&(((t == "text" || t == "textarea" || t == "password") && (vReadOnly == true || vDisabled == true))  || t == "file"))
            || ((ev.ctrlKey) && ((ev.keyCode == 78) || (ev.keyCode == 82))) || // CtrlN,CtrlR
            (ev.keyCode == 116); //F5

    //当敲Backspace键时，事件源类型非密码或单行、多行文本、文件的，则退格键失效
    var flag2 = (ev.keyCode == 8 && t != "text" && t != "textarea" && t != "password" && t != "file")
    || ((ev.ctrlKey) && ((ev.keyCode == 78) || (ev.keyCode == 82))) || // CtrlN,CtrlR
    (ev.keyCode == 116);

    if (flag1 || flag2) {
        ev.returnValue = false;
        if (ev.preventDefault) {  //阻止默认行为(ie9以下不支持，要进行判断)
            ev.preventDefault();
        }
    }
}


